package q14_longestCommonPrefix;

public class Solution {
    public static void main(String[] args) {
        String[] strs = {"dog","racecar","car"};
        System.out.println(longestCommonPrefix(strs));

    }

    public static String longestCommonPrefix(String[] strs) {
        StringBuilder res = new StringBuilder();

        int shortest = strs[0].length();
        // 找最短字符串
        for (int i = 0; i < strs.length; i++) {
            shortest = Math.min(shortest, strs[i].length());
        }

        if (shortest == 0) {
            return "";
        }else {
            for (int i = 0; i < shortest ; i++) {
                if (!"".equals(CommonCharCom(strs,i))) {
                    res.append(CommonCharCom(strs,i));
                }else {
                    return res.toString();
                }

            }
        }

        return res.toString();
    }

    public static String CommonCharCom(String[] strs, int i){
        String def = String.valueOf(strs[0].charAt(i));

        for (int j = 0; j < strs.length; j++) {
            if (!def.equals(String.valueOf(strs[j].charAt(i)))) {
                return "";
            }
        }
        // System.out.println(def);
        return def;

    }
}
